<?php
$username = $_POST['username'];
$petname = $_POST['petname'];
$password = $_POST['pwd'];
$repassword = $_POST['repwd'];

if ($username == '') {
    echo '<script>alert("请输入用户名！");history.go(-1);</script>';
    exit(0);
}
if ($password == '') {
    echo '<script>alert("请输入密码");history.go(-1);</script>';
    exit(0);
}
if ($petname == '') {
    echo '<script>alert("请输入昵称");history.go(-1);</script>';
    exit(0);
}
if ($password != $repassword) {
    echo '<script>alert("两次密码不一致");history.go(-1);</script>';
    exit(0);
}
if (strlen($username) > 16 || strlen($password) > 16 || strlen($petname) > 16){
    echo '<script>alert("不能超过16个字符");history.go(-1);</script>';
    exit(0);
}
if (strlen($password) < 6){
    echo '<script>alert("密码过短");history.go(-1);</script>';
    exit(0);
}
if ($password == $repassword) {
    include('./connect.php');
    if ($conn->connect_error) {
        echo '数据库连接失败！';
        exit(0);
    } else {
        $sql = "select username from user where username = '$username'";
        $result = $conn->query($sql);
        if (!$result) {
            echo '<script>alert("输入错误");</script>';
            // printf("Error: %s\n", mysqli_error($conn)); //打印错误信息
            exit();
        }
        $number = mysqli_num_rows($result);
        if ($number) {
            echo '<script>alert("用户名已经存在");history.go(-1);</script>';
        } else {
            $sql_insert = "insert into user (username,pwd,petname) values('$username','$password','$petname')";
            $res_insert = $conn->query($sql_insert);

            $sql_cata_insert = "insert into cata (cata_name,cata_user) values('默认收藏夹','$username')";
            $res_cata_insert = $conn->query($sql_cata_insert);
            if (!$res_cata_insert){
                echo "<script>alert('系统繁忙，请稍候！');</script>";
            }
            
            if ($res_insert) {
                echo "<script>localStorage.setItem('kusername','$username')</script>";
                echo "<script>localStorage.setItem('kpassword','$password')</script>";
                echo '<script>window.location="login.html";</script>';
            } else {
                // echo $res_insert;
                echo "<script>alert('系统繁忙，请稍候！');</script>";
            }
        }
    }
} else {
    echo "<script>alert('提交未成功！'); history.go(-1);</script>";
}
?>